'use strict';
const pkgDir = require('pkg-dir').sync
const fsExtra = require('fs-extra')
const path = require('path')
const fs = require('fs')
const npminstall = require('npminstall')
const pathExists = require('path-exists').sync
const {isObject} = require('@baseh-cli-dev/utils')
const formatPath = require('@baseh-cli-dev/format-path')
const {getDefaultRegistry, getNpmLastestVersion} = require('@baseh-cli-dev/get-npm-info')

class Package {
  constructor (options) {
    if (!options) {
      throw new Error('Package类的options参数不能为空')
    }
    if (!isObject(options)) {
      throw new Error('Package类的options参数必须为对象')
    }
    // package 的路基径
    this.targetPath = options.targetPath

    this.storeDir = options.storeDir
    this.packageName = options.packageName
    this.packageVersion = options.packageVersion

    this.cacheFilePathPrefix = this.packageName.replace('/', '-')
  }

  async prepare () {
    if (this.storeDir && !pathExists(this.storeDir)) {
      fsExtra.mkdirpSync(this.storeDir)
    }
    if (this.packageVersion === 'latest') {
      //this.packageVersion = await getNpmLastestVersion(this.packageName)
    }

    console.log('11111', this.packageVersion)
  }

  get cacheFilePath () {
    return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`)
  }

  getSpeficCacheFilePath (packageVersion) {
    return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${packageVersion}@${this.packageName}`)
  }

  // 判断当前package是否存在
  async exists () {
    if (this.storeDir) {
      await this.prepare()
      return pathExists(this.cacheFilePath)
    } else {
      return pathExists(this.targetPath)
    }
  }

  // 安装
  async install () {
    await this.prepare()
    // npminstall 4.10.0
    return npminstall({
      root: this.targetPath,
      storeDir: this.storeDir,
      registry: getDefaultRegistry(),
      pkgs: [
        {name: this.packageName, version: this.packageVersion}
      ]
    })
  }

  // 更新
  async update () {
    await this.prepare()
    // 获取最新的npm版本号
    const latestPackageVersion = await getNpmLastestVersion(this.packageName)
    const latestFilePath = this.getSpeficCacheFilePath(latestPackageVersion)
    if (!pathExists(latestFilePath)) {
      await npminstall({
        root: this.targetPath,
        storeDir: this.storeDir,
        registry: getDefaultRegistry(),
        pkgs: [
          {name: this.packageName, version: latestPackageVersion}
        ]
      })
      this.packageVersion = latestPackageVersion
    }
    return latestFilePath
  }

  // 获取入口文件的路径
  getRootFilePath () {
    function _getRootFile (targetPath) {
      // 1 获取package.json 所在目录 - pkg-dir
      const dir = pkgDir(targetPath)
      // 2. 读取package.json - require()
      if (dir) {
        // 3 main / lib - path
        const pkgFile = require(path.resolve(dir, 'package.json'))
        if (pkgFile && (pkgFile.main)) {
          return formatPath(path.resolve(dir, pkgFile.main))
        }
        // 4 路径兼容 (mac /windows)
      }
      return null
    }

    if (this.storeDir) {
      return _getRootFile(this.cacheFilePath)
    } else {
      return _getRootFile(this.targetPath)
    }
  }
}

module.exports = Package;